package com.terminee.resources;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.google.appengine.repackaged.org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.terminee.dataaccess.DatabaseDAO;
import com.terminee.factories.DatabaseDAOFactory;
import com.terminee.factories.TermineeDAOFactory;
import com.terminee.model.ClientObjectCounts;
import com.terminee.model.ClientTerm;
import com.terminee.model.Term;

@Path("/terminee")
public class TermineeResource {
	
	@Path("/get")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getTerm(@QueryParam("word") @DefaultValue("") String word) {
		
		List<ClientTerm> matchedTerms = new ArrayList<ClientTerm>();
		
		// if no word return empty array
		if(word.isEmpty()) {
			Gson gson = new Gson();
	        return gson.toJson(matchedTerms);
		}
		
		// get results from db
		DatabaseDAOFactory databaseFactory = new TermineeDAOFactory();
        DatabaseDAO termDAO = databaseFactory.getDAO(TermineeDAOFactory.TERM_WORD);
        Object result = termDAO.performRead(word, null);
        
        // prepare objects to be transfered to client by converting to client-side model objects
        // make sure result is a list
        if(result instanceof List<?>) {
        	List<Term> results = (List<Term>)result;
        	
        	// turn results into their client acceptable representations
        	if(results.size() > 0) {
        		for(Term matchedTerm : results) {
        			matchedTerms.add(matchedTerm.getClientTerm());
        		}
        	}
        }
        
        // turn into JSON and send to client
        Gson gson = new Gson();
        return gson.toJson(matchedTerms);
	}

	@Path("/add")
    @POST
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces(MediaType.TEXT_PLAIN)
    public String addTerm(@DefaultValue("") String json) {
	
		Boolean added = false;
		
		// if no json return false
		if(json.isEmpty()) {
	        return added.toString();
		}
		
		// convert from json to object
		Gson gson = new Gson();
		Term term;
		try {
			term = new Term(gson.fromJson(json, ClientTerm.class));
		} catch(JsonSyntaxException jse) {
			return added.toString();
		}
		
		// save term to db
		DatabaseDAOFactory databaseFactory = new TermineeDAOFactory();
        DatabaseDAO termDAO = databaseFactory.getDAO(TermineeDAOFactory.TERM_WORD);
        added = termDAO.performCreate(term);
		
		return added.toString();
	}
	
}
